package com.it.App.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.App.entity.LoginUser;
import com.it.App.entity.SysUser;
import com.it.App.exception.BaseException;
import com.it.App.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: CaoYouGen
 * @DateTime: 2023/11/22/13:01
 * @注释: TODO
 **/
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 登录验证
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        QueryWrapper<SysUser> wrapper = userQueryWrapper.eq("username", username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        // 是否查询到用户, 如果没有查询到永固抛出异常
        if (ObjectUtil.isNull(sysUser)){

           throw new BaseException("用户名或密码错误");
        }
        // 根据 用户id 从数据库中查询权限
        List<String> auths = sysUserMapper.getMenuByUserId(sysUser.getId());
        // 将查询出来的用户封装成UserDetails返回
        return LoginUser.builder().sysUser(sysUser).auths(auths).build();
    }
}
















